const { tokenIsValid, CustomError } = require('../core/common')
const {TokenNoFormat}=require("../config/errorCode")
const User = require('../model/user')
// auth 鉴权中间件
const auth = async (ctx, next) => {
  const access_token = ctx.headers.authorization || ''
  console.log('access_token', access_token)
  const decode = tokenIsValid(access_token)
  if (decode) {
    const user = await User.findByPk(decode.uid)
    if (user) {
      ctx.auth = { uid: decode.uid, user }
      await next()
    } else {
      throw new CustomError('用户不存在', TokenNoFormat)
    }
  }
}
module.exports = auth
